/* wifi-kii, a tool to set a Wii's wifi key from SD/USB
   Copyright (C) 2010  smoere (smoere@gmail.com)

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
	
*/
	
/* 	this project includes other peoples code. i'll try to leave thoses copyrightheaders intact
	
	UNSTABLE UNTILL THIS LINE IS REMOVED
*/

#define WRITETEST false

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <gccore.h>
#include <wiiuse/wpad.h>
#include <ogc/isfs.h>
#include <fat.h>

#include "sha1.h"
#include "pbkdf2.h"
#include "netsetlayout.h"

static void *xfb = NULL;
static GXRModeObj *rmode = NULL;

s32 __IOS_LoadStartupIOS() //blocking iosreload 36 on older libogc versions
{
return 0;
}

void SHA1(char *input, int size, char *output) {
  SHA1_CTX ctx;
  SHA1Init(&ctx);
  SHA1Update(&ctx, input, size);
  SHA1Final(output, &ctx);
}

void sanitycheck(){
	printf("let's do some sanity checks:\n");
	
	char* result = (char *)malloc(sizeof(char)*21);
	if (result==NULL){
		printf("couldn't allocate mem for the sha1 test");
		return;
	}
	char testcase1[20]={0xA9, 0x99, 0x3E, 0x36, 0x47, 0x06, 0x81, 0x6A, 0xBA, 0x3E, 0x25, 0x71, 
			0x78, 0x50, 0xC2, 0x6C, 0x9C, 0xD0, 0xD8, 0x9D};
	char testcase2[20]={0x84, 0x98, 0x3E, 0x44, 0x1C, 0x3B, 0xD2, 0x6E, 0xBA, 0xAE, 0x4A, 0xA1,
			0xF9, 0x51, 0x29, 0xE5, 0xE5, 0x46, 0x70, 0xF1};
	SHA1("abc",3,result); 
	if (memcmp(result, testcase1, 20)!=0){
		printf("sha1 failed testcase 1");
	}
	
	SHA1("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",56,result);
	if (memcmp(result, testcase2, 20)!=0){
		printf("sha1 failed testcase 2");
	}
	
	free(result);
	
	printf("pbkdf2:\n");
	if (testpbkdf2()) printf("pbkdf2 not sane.");
	else printf("pbkdf2 sane.");
	fflush(stdout);
   
}

void init(){
	// Initialise the video system
	VIDEO_Init();
	
	// This function initialises the attached controllers
	WPAD_Init();
	PAD_Init();
	WPAD_SetDataFormat(WPAD_CHAN_0, WPAD_FMT_BTNS_ACC_IR);					

	// Obtain the preferred video mode from the system
	// This will correspond to the settings in the Wii menu
	rmode = VIDEO_GetPreferredMode(NULL);

	// Allocate memory for the display in the uncached region
	xfb = MEM_K0_TO_K1(SYS_AllocateFramebuffer(rmode));
	
	// Initialise the console, required for printf
	console_init(xfb,20,20,rmode->fbWidth,rmode->xfbHeight,rmode->fbWidth*VI_DISPLAY_PIX_SZ);
	
	// Set up the video registers with the chosen mode
	VIDEO_Configure(rmode);
	
	// Tell the video hardware where our display memory is
	VIDEO_SetNextFramebuffer(xfb);
	
	// Make the display visible
	VIDEO_SetBlack(FALSE);

	// Flush the video register changes to the hardware
	VIDEO_Flush();

	// Wait for Video setup to complete
	VIDEO_WaitVSync();
	if(rmode->viTVMode&VI_NON_INTERLACE) VIDEO_WaitVSync();

	
	// The console understands VT terminal escape codes
	// This positions the cursor on row 2, column 0
	// we can use variables for this with format codes too
	// e.g. printf ("\x1b[%d;%dH", row, column );
	printf("\x1b[2;0H");
}


//---------------------------------------------------------------------------------
int main(int argc, char **argv){
//---------------------------------------------------------------------------------

	int file,retval,size;
	bool oksofar;
	char* newkey,passphrase;
	netconfig_t* netconfig;
	char* buffer;
	u32 *ownerID;
	u16 *groupID;
	u8* attributes, ownerperm, groupperm, otherperm;
	
	init();
	oksofar = true;
	file = -1;
	retval = -1;


	netconfig = (netconfig_t *)memalign(32,7008);
	if (netconfig==NULL){
		printf("couldn't allocate mem for \"netconfig\"");
		return -1;
	}

	newkey = (char *)malloc(sizeof(char)*257);
	if (newkey==NULL){
		printf("couldn't allocate mem for \"newkey\"");
		return -1;
	}

	passphrase = (char *)malloc(sizeof(char)*65);
	if (passphrase==NULL){
		printf("couldn't allocate mem for \"passphrase\"");
		return -1;
	}
	
	strcpy(passphrase, "tuetensuppe!");

///////////////////////////////////////////////////////////////////////////
	printf("wifi-kii phase 1: read test\n");
//	sanitycheck();
	
	if(oksofar){
		retval = sizeof(netconfig_t);
		if(retval !=7004){
			printf("\nError: sizeof(netconfig_t) = %d\n", retval);
			oksofar=false;
		}
	}
	
	if(oksofar){
		retval = fatInitDefault();
		if(retval < 0){
			printf("\nError: fatInitDefault() returned %d\n", retval);
			oksofar=false;
		}
	}	
	
	if(oksofar){
		retval = ISFS_Initialize();
		if (retval < 0){
			printf("\nError: ISFS_Initialize() returned %d\n", retval);
			oksofar = false;
		}
	}
	
	if(oksofar){
		file = ISFS_Open("/shared2/sys/net/02/config.dat", ISFS_OPEN_READ);
		if (file < 0){
			printf("\nError: ISFS_OpenFile() returned %d\n", file);
			oksofar = false;
		}
	}
	
	if(oksofar){
		retval = ISFS_Read(file, netconfig, sizeof(netconfig_t));
		if (retval < 0){
			printf("\nError: ISFS_Read() returned %d\n", retval);
			oksofar = false;
		}
	}

	if(oksofar){
		retval = ISFS_Close(file);
		if (retval < 0){
			printf("\nError: ISFS_Close() returned %d\n", retval);
			oksofar = false;
		}
	}

	retval = ISFS_GetAttr("/shared2/sys/net/02/config.dat", ownerID, groupID, attributes, ownerperm, groupperm, otherperm);
	if (retval < 0) printf("\nError: ISFS_GetAttr() returned %d\n", retval);
	printf("\n DEBUG %d %d %d %d %d %d\n ",ownerID, groupID, attributes, ownerperm, groupperm, otherperm);
	
	if(WRITETEST){
		file=NULL;
		retval = ISFS_CreateFile("/shared2/sys/net/02/config.new", 0, 3, 1, 1); //attributes, ownerperm, groupperm, otherperm);
		if (retval < 0) printf("\nError: WRITETEST ISFS_Createfile() returned %d\n", retval);
		file=ISFS_Open("/shared2/sys/net/02/config.new", ISFS_OPEN_WRITE);
		if (file==NULL) printf("\nError: WRITETEST ISFS_Open() returned %d\n", retval);
		retval = ISFS_Write(file, netconfig, sizeof(netconfig_t));
		if (retval < 0) printf("\nError: WRITETEST ISFS_Write() returned %d\n", retval);
		retval = ISFS_Close(file);
		if (retval < 0) printf("\nError: WRITETEST ISFS_Close() returned %d\n", retval);
		retval = ISFS_Rename("/shared2/sys/net/02/config.new", "/shared2/sys/net/02/config.dat");
		if (retval < 0) printf("\nError: WRITETEST ISFS_Rename() returned %d\n", retval);
	}

	if(oksofar){
		retval = ISFS_Deinitialize();
		if (retval < 0){
			printf("\nError: ISFS_Deinitialize() returned %d\n", retval);
			oksofar = false;
		}
	}
	
	if(oksofar){
		printf("YAY! there were no errors encountered while reading the configfile.\n");
		printf("now lets see if the values we've read are right:\n");
		printf("the Wii ip of your first config should be: %d.%d.%d.%d\n", netconfig->connection[0].ip[0], 
			netconfig->connection[0].ip[1], netconfig->connection[0].ip[2], netconfig->connection[0].ip[3]); 
		printf("the Wii ip of your second config should be: %d.%d.%d.%d\n", netconfig->connection[1].ip[0], 
			netconfig->connection[1].ip[1], netconfig->connection[1].ip[2], netconfig->connection[1].ip[3]); 
		printf("\n");
		printf("the SSID of your first config should be: %s\n", (char*)netconfig->connection[0].ssid);
		if (pkcs5_pbkdf2(passphrase, strlen(passphrase), (char*)netconfig->connection[0].ssid, 
			strlen((char*)netconfig->connection[0].ssid), newkey, 256, 4096)!=0){
			printf("\nError: pbkdf2 failed");
		}
	}
	
	if(!oksofar){
		printf("dang. something went wrong. please let me know all the above errors.");
	}
	
	
	/////pbkdf2(passphrase, passphrase.length(), ssid, ssid.length(), convertedkey, 256, 4096)


	fflush(stdout);
	
	while(1) {

		// Call WPAD_ScanPads each loop, this reads the latest controller states
		WPAD_ScanPads();

		// WPAD_ButtonsDown tells us which buttons were pressed in this loop
		// this is a "one shot" state which will not fire again until the button has been released
		u32 pressed = WPAD_ButtonsDown(0);

		// We return to the launcher application via exit
		if ( pressed & WPAD_BUTTON_HOME ) exit(0);

		// Wait for the next frame
		VIDEO_WaitVSync();
	}

	return 0;
}
